<template>
    <el-dialog :model-value="show" @close="closeFn" style="width:500px;" title="分配角色">
        <el-select v-model="value1" multiple placeholder="请选择" style="width:100%;">
            <el-option v-for="item in options" :key="item.id" :label="item.name" :value="item.id" />
        </el-select>
        <template #footer>
            <el-button @click="closeFn">取消</el-button>
            <el-button type="primary" @click="allocRoleFn">确定</el-button>
        </template>
    </el-dialog>
</template>
<script setup lang='ts'>
import { ref, toRef, watch } from 'vue'
import { getAllRoleListApi, getRoleListByUserIdAPi, updateUserRoleApi } from '@/api'
import { ElMessage } from 'element-plus';
const props = defineProps({
    show: {
        type: Boolean,
        default: false
    },
    id: {
        type: Number,
        default: 0
    }
})
const id = toRef(props, 'id');
const value1 = ref<number[]>([])
const options = ref<IRoleModel[]>([])

watch(id, () => {
    if (id.value === 0) return;
    getRoleListByUserIdAPi(id.value).then(res => {
        if (res.code == 200) {
            let ids = res.data.map(item => item.id)
            value1.value.push(...ids)
        }
    })
})

// 获取所有的角色数据
getAllRoleListApi().then(res => {
    if (res.code === 200) {
        options.value = res.data
    }
})

const emit = defineEmits(['close']);
const closeFn = () => {
    emit('close');
    value1.value = [];
}

const allocRoleFn = () => {
    updateUserRoleApi({
        adminId: id.value, roleIds: value1.value
    }).then(res => {
        if (res.code == 200) {
            ElMessage({
                type: 'success',
                message: '修改成功'
            })
            closeFn();
        }
    })
}

</script>
<style lang="less" scoped></style>